package com.yangxiangrice.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.xerces.internal.dom.PSVIDocumentImpl;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import com.yangxiangrice.pojo.Result;
import com.yangxiangrice.pojo.SeedList;
import com.yangxiangrice.pojo.UserList;
import com.yangxiangrice.service.AgItemsService;
import com.yangxiangrice.service.MenuService;
import com.yangxiangrice.service.SeedListService;
import com.yangxiangrice.service.UserListService;
import com.yangxiangrice.util.SaltUtil;
import javafx.scene.chart.ValueAxis;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: TODO
 * @author: shixiaojian
 * @date: 2021年11月16日 22:17
 */
@Controller
@RequestMapping("/userlist")
@CrossOrigin
@Slf4j
public class UserListController {
    @Autowired
    UserListService userListService;
    @Autowired
    MenuService menuService;
    @Autowired
    SeedListService seedListService;
    @Autowired
    AgItemsService agItemsService;

    @PostMapping(value = "/login")
    @ResponseBody
    public Result login(@RequestBody UserList user, @RequestParam(value = "rememberpwd") Boolean rememberMe) {
        Result<UserList> result = new Result<>();
        String phone = user.getPhone();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(phone, user.getPasswd());
        token.setRememberMe(rememberMe);
        try {
            subject.login(token);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("phone", subject.getPrincipal());
            UserList userList = userListService.getOne(wrapper);
            QueryWrapper wrapper_new = new QueryWrapper();
            wrapper_new.eq("userType", userList.getUserType());
            List list = menuService.list(wrapper_new);
            result.ok(userList, token, list);
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
            result.fail("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            result.fail("密码错误");
        }
        return result;
    }

    @RequestMapping(value = "/logout")
    @ResponseBody
    public Result logout() {
        Result<String> result = new Result();
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.logout();
            String msg = "退出成功";
            result.ok(msg);
        } catch (Exception e) {
            result.fail("退出失败");
        }
        return result;
    }

    @GetMapping(value = "/listpage")
    @ResponseBody
    public Result listpage(@RequestParam("page") int page,
                           @RequestParam("limit") int limit) {
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        Result<IPage> result = new Result<>();
        IPage<UserList> userListIPage = userListService.seletePage(new Page<>(page, limit), null);
        return result.ok(userListIPage);
    }

    @PostMapping(value = "/save")
    @ResponseBody
    public Result save(@RequestBody UserList userList) {
        Result<Boolean> result = new Result<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", userList.getPhone());
        if (ObjectUtil.isEmpty(userList.getUserId())) {
            if (userListService.count(wrapper) > 0) {
                result.fail("手机号已存在，请重新输入");
            } else {
                String salt = SaltUtil.getSalt(8);
                Md5Hash md5Hash = new Md5Hash("123456", salt, 1024);
                userList.setSalt(salt);
                userList.setPasswd(md5Hash.toHex());
                userList.setCreatetime(new Timestamp(System.currentTimeMillis()));
                boolean tag = userListService.save(userList);
                if (tag) {
                    result.ok(tag);
                } else {
                    result.fail("添加失败，请重试");
                }
            }
        } else {
            if (userListService.count(wrapper) > 0) {
                result.fail("手机号已存在，请重新输入");
            }else{
                userList.setCreatetime(new Timestamp(System.currentTimeMillis()));
                boolean tag = userListService.updateById(userList);
                if (tag) {
                    result.ok(tag);
                } else {
                    result.fail("更新失败，请重试");
                }
            }
        }
        return result;
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam(value = "userId") Integer userId) {
        Result<Boolean> result = new Result<>();
        boolean tag = userListService.removeById(userId);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("删除失败");
        }
        return result;
    }

    @PostMapping(value = "/deleteBatch")
    @ResponseBody
    public Result deleteBatch(@RequestBody int[] ids) {
        ArrayList<Integer> list = new ArrayList<>();
        Result<Boolean> result = new Result<>();
        for (int id : ids) {
            list.add(id);
        }
        boolean tag = userListService.removeByIds(list);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("删除失败");
        }
        return result;
    }

    @PostMapping(value = "/resetpwd")
    @ResponseBody
    public Result resetPwd(@RequestParam(value = "userId") Integer userId) {
        Result<Boolean> result = new Result<>();
        String newsalt = SaltUtil.getSalt(8);
        String newpass = new SimpleHash("md5", "123456", newsalt, 1024).toString();
        if (userListService.changePwd(userId, newpass, newsalt)) {
            result.setMessage("密码修改成功");
            result.ok(true);
        } else {
            result.fail("密码重置失败，请重试");
        }
        return result;
    }

    @PostMapping(value = "/changepwd")
    @ResponseBody
    public Result changepwd(@RequestParam("phone") String phone,
                            @RequestParam("oldPasswd") String oldPasswd,
                            @RequestParam("confirmPasswd") String confirmPasswd) {
        Result<Boolean> result = new Result<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        UserList userList = userListService.getOne(wrapper);
        String passwd = userList.getPasswd();
        String oldsalt = userList.getSalt();
        if (!passwd.equals(new SimpleHash("md5", oldPasswd, oldsalt, 1024).toString())) {
            result.fail("原密码错误，请重新输入");
        } else {
            String newsalt = SaltUtil.getSalt(8);
            String newpass = new SimpleHash("md5", confirmPasswd, newsalt, 1024).toString();
            System.out.println(newpass);
            if (userListService.changePwd(userList.getUserId(), newpass, newsalt)) {
                result.setMessage("密码修改成功");
                result.ok(true);
            } else {
                result.fail("密码修改失败，请重试");
            }
        }
        return result;
    }

    @RequestMapping(value = "/search")
    @ResponseBody
    public Result search(@RequestParam("input") String input,
                         @RequestParam("page") int page,
                         @RequestParam("limit") int limit) {
        Result<IPage> result = new Result<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("realname", input);
        IPage<UserList> userListIPage = userListService.seletePage(new Page<>(page, limit), wrapper);
        if (ObjectUtil.isEmpty(userListIPage)) {
            result.fail("未找到符合条件的数据");
        } else {
            result.ok(userListIPage);
        }
        return result;
    }

    @GetMapping(value = "/getnum")
    @ResponseBody
    public List getnum() {
        ArrayList list = new ArrayList();
        Integer adminNum = userListService.getAdminNum();
        Integer farmerNum = userListService.getFarmerNum();
        Integer seedNum = seedListService.getSeedNum();
        Integer agitemNum = agItemsService.getAgitemNum();
        list.add(adminNum);
        list.add(farmerNum);
        list.add(seedNum);
        list.add(agitemNum);
        return list;
    }

}
